<template>
    <div class="login-container">
        <div class="login-bg-section">
            <img src="../../assets/login/login-bg.png" alt="登录背景图" class="login-bg">
            <img src="../../assets/login/logo.png" alt="LOGO图" class="logo">
        </div>

        <div class="login-form-section">
            <TitleBar class="title-bar" />

            <div class="form-container">
                <el-card class="login-card">
                    <div class="login-header">
                        <h2>欢迎使用小鹿线管理系统</h2>
                    </div>

                    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form"
                        @keyup.enter="handleLogin">
                        <el-form-item prop="username">
                            <el-input v-model="loginForm.username" placeholder="请输入您的账号" />
                        </el-form-item>

                        <el-form-item prop="password">
                            <el-input v-model="loginForm.password" type="password" placeholder="请输入您的密码"
                                show-password />
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" class="login-submit-btn" :loading="loading" @click="handleLogin">
                                登录
                            </el-button>
                        </el-form-item>
                    </el-form>

                    <div class="login-footer">
                        登录即同意<a href="#">《小鹿线用户服务协议》</a><a href="#">《小鹿线隐私政策》</a>
                    </div>
                </el-card>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../../stores/auth'
import TitleBar from '../../components/layout/TitleBar.vue'

const router = useRouter()
const authStore = useAuthStore()

const loginFormRef = ref(null)

const loginForm = reactive({
    username: '',
    password: ''
})

const loginRules = reactive({
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ]
})

const loading = ref(false)

// 页面加载时检查authAPI是否可用
onMounted(() => {
    if (window.authAPI?.setAuthToken) { } else {
        console.error('❌ login.vue: authAPI.setAuthToken 不可用！请检查preload.js')
        ElMessage.warning('系统初始化警告：推送服务可能无法使用')
    }
})

const handleLogin = async () => {
    try {
        if (!loginFormRef.value) {
            throw new Error('表单未初始化')
        }

        await loginFormRef.value.validate()
        loading.value = true

        // 执行登录
        await authStore.login(loginForm)

        // 登录成功后传递token到主进程
        if (window.authAPI?.setAuthToken) {
            const token = authStore.token
            if (token) {
                window.authAPI.setAuthToken(token)
            } else {
                console.error('❌ login.vue: authStore.token 为空')
                ElMessage.warning('登录成功，但未获取到认证信息')
            }
        } else {
            console.error('❌ login.vue: 无法访问authAPI.setAuthToken')
            ElMessage.warning('登录成功，但推送服务初始化失败')
        }

        // 跳转页面
        const redirectPath = router.currentRoute.value.query.redirect || '/'
        await router.push(redirectPath)

        ElMessage.success('登录成功')
    } catch (error) {
        console.error('登录失败:', error)
        if (error.message === '表单未初始化') {
            ElMessage.error('系统错误，请刷新页面')
        } else if (error?.errors?.length) {
            ElMessage.warning(error.errors[0].message)
        } else {
            ElMessage.error(error.response?.data?.message || '登录失败，请检查账号密码')
        }
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
.login-form-section .title-bar {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 10;
}

.login-form-section {
    position: relative;
    padding-top: 60px;
}

.login-container {
    display: flex;
    height: 100vh;
    background-color: #F2F3FA;
}

.login-bg-section {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    position: relative;
}

.login-bg {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.logo {
    width: 48px;
    height: 48px;
    cursor: pointer;
    position: absolute;
    left: 40px;
    top: 40px;
    transition: transform 0.2s;
}

.logo:hover {
    transform: scale(1.05);
}

.login-form-section {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
}

.login-card {
    width: 400px;
    padding: 30px;
    border: none;
    box-shadow: none;
}

.login-header {
    text-align: left;
    margin-bottom: 30px;
}

.login-header h2 {
    color: #333;
    font-size: 24px;
    font-weight: 500;
}

.login-form {
    margin-top: 20px;
}

.login-submit-btn {
    width: 100%;
    margin-top: 20px;
    height: 40px;
}

.login-footer {
    margin-top: 30px;
    font-size: 12px;
    color: #999;
    text-align: center;
    line-height: 1.5;
}

.login-footer a {
    color: #409eff;
    text-decoration: none;
    margin: 0 5px;
}

.login-form :deep(.el-input) {
    box-sizing: border-box;
    height: 48px;
}

.login-form :deep(.el-input__wrapper) {
    height: 48px;
    box-sizing: border-box;
}

.el-form-item {
    margin-bottom: 24px;
}

@media (max-width: 768px) {
    .login-container {
        flex-direction: column;
    }

    .login-bg-section {
        display: none;
    }

    .login-form-section {
        padding: 20px;
        padding-top: 60px;
    }

    .login-card {
        width: 100%;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
}
</style>